import React from 'react';
import { LinkOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin, Select, message, Button, Table } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import QutDetail from './QutDetail';

const { Option } = Select;
const FormItem = Form.Item;

@connect(({ loading, batchquo }) => ({
  loading: loading.models.addemp || loading.effects['batchquo/fetchQuoInfo'] || false,
  batchquo,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      suppId: null, // 签约方Id
      custId: null, // 客户Id
      suppContId: null, // 供应商合同Id
      modalVisible: false,
    };
  }

  componentDidMount() {
    // 获取当前角色所在公司对应的平台供应商
    const {
      dispatch,
      form,
      batchquo: { isGoBack = false },
    } = this.props;
    if (!isGoBack) {
      dispatch({
        type: 'batchquo/updateModelData',
        payload: {
          isSameComy: true,
          quoPdList: [],
        },
      });
      dispatch({
        type: 'batchquo/updateQuery',
        payload: {
          sendSuppId: undefined,
          contId: undefined,
          custId: undefined,
          oldQuoId: undefined,
          quoId: undefined,
        },
      });
      dispatch({
        type: 'batchquo/updateModelData',
        payload: {
          supplyList: [],
          customerNameList: [],
          supplyContList: [],
          contList: [],
          quoList: [],
        },
      });
      dispatch({
        type: 'publicdata/fetchDictCode',
        payload: ['PAY_FEES_WAY', 'BIZ_INS_TYPE', 'ISNULL_FLAG', 'PRODUCT_WAGE_TYPE', 'PD_CATE'],
      });
      dispatch({
        type: 'addemp/plasuppList',
        payload: {},
        callback: response => {
          if (response.success && response.data) {
            dispatch({
              type: 'batchquo/updateModelData',
              payload: { suppReplaceCorpId: response.data[0].suppId },
            });
            // 签约方(供应商)列表
            dispatch({
              type: 'addemp/contractParty',
              payload: { name: null, status: 2 },
              callback: r => {
                if (r.success && r.data) {
                  dispatch({
                    type: 'batchquo/updateModelData',
                    payload: { supplyList: r.data },
                  });

                  for (let index = 0; index < r.data.length; index += 1) {
                    const item = r.data[index];
                    if (response.data[0].suppId === item.suppId) {
                      form.setFieldsValue({ sendSuppId: item.suppId });
                      this.setState({
                        suppId: item.suppId,
                      });
                      this.getCustomers(item.suppId);
                      break;
                    }
                  }
                } else {
                  message.warning(`${r.message || '暂无数据！'}`);
                }
              },
            });
          }
        },
      });
    }
    dispatch({
      type: 'batchquo/updateModelData',
      payload: {
        isGoBack: false,
      },
    });
  }

  // 签约方选择 : 根据选择显示不同
  selectCompany = suppId => {
    const { form, dispatch, batchquo } = this.props;
    form.resetFields(['custId', 'contId', 'oldQuoId', 'quoId']);
    dispatch({
      type: 'batchquo/updateQuery',
      payload: {
        sendSuppId: suppId,
        contId: undefined,
        custId: undefined,
        oldQuoId: undefined,
        quoId: undefined,
      },
    });
    dispatch({
      type: 'batchquo/updateModelData',
      payload: {
        isSameComy: suppId === batchquo.suppReplaceCorpId,
        customerNameList: [],
        supplyContList: [],
        contList: [],
        quoList: [],
      },
    });
    if (suppId === batchquo.suppReplaceCorpId) {
      this.getCustomers(suppId); // 本地  请求客户名称
    } else {
      this.getSupplyers(suppId); // 全国 请求供应商合同
    }
    this.setState({ suppId });
  };

  // 选择签约方为本地：请求客户名称
  getCustomers = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/customerList',
      payload: {},
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'batchquo/updateModelData',
            payload: { customerNameList: response.data },
          });
        } else {
          message.warning('该签约方下暂无客户！');
        }
      },
    });
  };

  // 选择客户名称：请求商务合同
  selectCustomers = custId => {
    const { form } = this.props;
    const { dispatch } = this.props;
    form.resetFields(['contId', 'oldQuoId', 'quoId']);
    dispatch({
      type: 'batchquo/updateQuery',
      payload: {
        contId: undefined,
        oldQuoId: undefined,
        quoId: undefined,
      },
    });
    dispatch({
      type: 'batchquo/updateModelData',
      payload: { supplyContList: [], custId, contList: [], quoList: [] },
    });
    dispatch({
      type: 'addemp/getBusiness',
      payload: { custId, queryType: 3 },
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'batchquo/updateModelData',
            payload: { contList: response.data },
          });
        } else {
          message.warning('该客户名称下暂无商务合同！');
        }
      },
    });
  };

  // 选择商务合同：请求报价单
  selectCont = (custContId, options) => {
    const { dispatch, form } = this.props;
    const { suppId, custId } = this.state;
    if (options.props.state === 3) {
      message.warning('该商务合同已到期！');
    }
    form.resetFields(['oldQuoId', 'quoId']);
    dispatch({
      type: 'batchquo/updateQuery',
      payload: {
        oldQuoId: undefined,
        quoId: undefined,
      },
    });
    dispatch({
      type: 'batchquo/updateModelData',
      payload: { quoList: [] },
    });
    const pamList = {
      custContId,
      suppId,
      custId,
    };
    dispatch({
      type: 'addemp/getQuotation',
      payload: pamList,
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'batchquo/updateModelData',
            payload: { quoList: response.data },
          });
        } else {
          message.warning('该商务合同下无报价单！');
        }
      },
    });
  };

  // 根据签约方为全国：请求供应商合同
  getSupplyers = suppId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/getNameList',
      payload: { suppId, queryType: 3 },
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'batchquo/updateModelData',
            payload: { supplyContList: response.data },
          });
        } else {
          message.warning('暂无供应商合同列表');
        }
      },
    });
  };

  // 根据选择的供应商合同：请求客户名称
  selectSupply = (contId, options) => {
    const { dispatch } = this.props;
    const { form } = this.props;
    if (options.props.state === 3) {
      message.warning('该供应商合同已到期！');
    }
    this.setState({
      suppContId: contId,
    });
    form.resetFields(['custId', 'oldQuoId', 'quoId']);
    dispatch({
      type: 'batchquo/updateQuery',
      payload: {
        custId: undefined,
        oldQuoId: undefined,
        quoId: undefined,
      },
    });
    dispatch({
      type: 'batchquo/updateModelData',
      payload: { customerNameList: [], quoList: [] },
    });
    dispatch({
      type: 'addemp/getCustnameList',
      payload: { contId },
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'batchquo/updateModelData',
            payload: { customerNameList: response.data },
          });
        } else {
          message.warning('该供应商合同下无客户！');
        }
      },
    });
  };

  // 选择客户名称：请求报价单
  selectSuppCust = custId => {
    const { dispatch, form } = this.props;
    const { suppContId } = this.state;
    form.resetFields(['oldQuoId', 'quoId']);
    dispatch({
      type: 'batchquo/updateQuery',
      payload: {
        oldQuoId: undefined,
        quoId: undefined,
      },
    });
    dispatch({
      type: 'batchquo/updateModelData',
      payload: { quoList: [] },
    });
    dispatch({
      type: 'addemp/pleaseQun',
      payload: { custId, custContId: suppContId },
      callback: response => {
        if (response.success && response.data && response.data.length) {
          dispatch({
            type: 'batchquo/updateModelData',
            payload: { quoList: response.data },
          });
        } else {
          message.warning('该客户名称下无报价单！');
        }
      },
    });
  };

  // 选择报价单
  selectQuo = (value, id) => {
    const {
      dispatch,
      form,
      batchquo: { batchQuery },
    } = this.props;
    const getFieldsList = form.getFieldsValue();
    dispatch({
      type: 'batchquo/updateQuery',
      payload: {
        [id]: value,
      },
    });
    if ((id === 'oldQuoId' && getFieldsList.quoId) || (id === 'quoId' && getFieldsList.oldQuoId)) {
      dispatch({
        type: 'batchquo/getPdList',
        payload: {
          quoId: id === 'oldQuoId' ? value : batchQuery.oldQuoId,
          newQuoId: id === 'quoId' ? value : batchQuery.quoId,
        },
      });
    }
  };

  // 模态框显隐
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  // 获取报价单信息
  getQuoDetail = quoId => {
    if (!quoId) {
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'batchquo/fetchQuoInfo',
      payload: { quoId },
    }).then(response => {
      if (response.success) {
        this.setState({ modalVisible: true });
      } else {
        message.warning(`${response.message || '获取报价单信息：服务端错误！'}`);
      }
    });
  };

  // 下一步
  nextStep = () => {
    const { form, onNext, dispatch } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.oldQuoId === values.quoId) {
          return message.warning('请选择不同的报价单！');
        }
        Object.keys(values).forEach(key => {
          const temp = values;
          if (values[key] && values[key].key) {
            temp[key] = values[key].key;
          } else {
            temp[key] = values[key] ? values[key] : '';
          }
        });
        const quoInfo = { ...values };
        dispatch({
          type: 'batchquo/updateQuery',
          payload: { ...quoInfo },
        });
        onNext(quoInfo);
      }
      return true;
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      batchQuery,
      batchquo: {
        isSameComy,
        customerNameList,
        supplyContList,
        contList,
        quoList,
        supplyList,
        quoPdList,
        detailInfo,
      },
      loading,
    } = this.props;
    const { modalVisible } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const pdColumns = [
      {
        title: '产品',
        dataIndex: 'pdName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '原报价单',
        dataIndex: 'oldQuo',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        children: [
          {
            title: '有无对应产品',
            dataIndex: ['oldQuo','hasPro'],
            align: 'center',
            width: 150,
            onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
            render: val => <span>{val ? '有' : '无'}</span>,
          },
          {
            title: '属性',
            dataIndex: ['oldQuo','attrList'],
            onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
            render: (val, record) => (
              <div>
                {(record.oldQuo &&
                  record.oldQuo.hasPro &&
                  val &&
                  val.length &&
                  val.map(attr => (
                    <p key={attr.attrTitle}>
                      {attr.attrTitle}:{attr.attrValName}
                    </p>
                  ))) || <p style={{ textAlign: 'center' }}>--</p>}
              </div>
            ),
          },
        ],
      },
      {
        title: '新报价单',
        dataIndex: 'newQuo',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        children: [
          {
            title: '有无对应产品',
            dataIndex: ['newQuo','hasPro'],
            align: 'center',
            width: 150,
            onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
            render: (val, record) => (
              <span style={{ color: record.newQuo.diff ? '#f90' : 'rgba(0, 0, 0, 0.65)' }}>
                {val ? '有' : '无'}
              </span>
            ),
          },
          {
            title: '属性',
            dataIndex: ['newQuo','attrList'],
            onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
            render: (val, record) => (
              <div>
                {(record.newQuo &&
                  record.newQuo.hasPro &&
                  val &&
                  val.length &&
                  val.map(attr => (
                    <p
                      key={attr.attrTitle}
                      style={{ color: attr.diff ? '#f90' : 'rgba(0, 0, 0, 0.65)' }}
                    >
                      {attr.attrTitle}:{attr.attrValName}
                    </p>
                  ))) || <p style={{ textAlign: 'center' }}>--</p>}
              </div>
            ),
          },
        ],
      },
    ];
    const SelelctCust = () => {
      if (isSameComy) {
        return (
          <div>
            <FormItem {...formItemLayout} label="客户名称">
              {getFieldDecorator('custId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: batchQuery.custId,
              })(
                <Select
                  placeholder="请选择"
                  onSelect={this.selectCustomers}
                  showSearch
                  optionFilterProp="children"
                >
                  {customerNameList.map(one => (
                    <Option key={one.custId} value={one.custId} title={one.name}>
                      {one.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="商务合同">
              {getFieldDecorator('contId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: batchQuery.contId,
              })(
                <Select
                  placeholder="请选择"
                  onSelect={(value, options) => this.selectCont(value, options)}
                  showSearch
                  optionFilterProp="children"
                >
                  {contList.map(one => (
                    <Option
                      key={one.contId}
                      value={one.contId}
                      state={one.contState}
                      title={one.contName}
                    >
                      {one.contName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </div>
        );
      }
      return (
        <div>
          <FormItem {...formItemLayout} label="供应商合同">
            {getFieldDecorator('contId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: batchQuery.contId,
            })(
              <Select
                placeholder="请选择"
                onSelect={(value, options) => this.selectSupply(value, options)}
                showSearch
                optionFilterProp="children"
              >
                {supplyContList.map(one => (
                  <Option
                    key={one.contId}
                    value={one.contId}
                    state={one.contState}
                    title={one.contName}
                  >
                    {one.contName}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="客户名称">
            {getFieldDecorator('custId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: batchQuery.custId,
            })(
              <Select
                placeholder="请选择"
                onSelect={this.selectSuppCust}
                showSearch
                optionFilterProp="children"
              >
                {customerNameList.map(one => (
                  <Option key={one.custId} value={one.custId} title={one.name}>
                    {one.name}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
        </div>
      );
    };
    return (
      <Form style={{ margin: '40px auto 0', maxWidth: 800 }}>
        <Spin tip="Loading..." spinning={loading}>
          <FormItem {...formItemLayout} label="签约方">
            {getFieldDecorator('sendSuppId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: batchQuery.sendSuppId,
            })(
              <Select
                placeholder="请选择"
                onSelect={this.selectCompany}
                showSearch
                optionFilterProp="children"
              >
                {supplyList.map(one => (
                  <Option key={one.suppId} value={one.suppId} title={one.name}>
                    {one.name}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
          <SelelctCust />
          <div style={{ position: 'relative' }}>
            <FormItem {...formItemLayout} label="原报价单">
              {getFieldDecorator('oldQuoId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: batchQuery.oldQuoId,
              })(
                <Select
                  placeholder="请选择"
                  onSelect={value => this.selectQuo(value, 'oldQuoId')}
                  showSearch
                  optionFilterProp="children"
                >
                  {quoList.map(one => (
                    <Option
                      key={one.quoId}
                      value={one.quoId}
                      sertype={one.serType}
                      title={one.quoName}
                    >
                      {one.quoName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <LinkOutlined
              style={{
                color: batchQuery.oldQuoId ? '#40a9ff' : 'rgb(206, 206, 206)',
                fontSize: '24px',
                position: 'absolute',
                top: '8px',
                right: '190px',
              }}
              onClick={() => this.getQuoDetail(batchQuery.oldQuoId)} />
          </div>
          <div style={{ position: 'relative' }}>
            <FormItem {...formItemLayout} label="新报价单">
              {getFieldDecorator('quoId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: batchQuery.quoId,
              })(
                <Select
                  placeholder="请选择"
                  onSelect={value => this.selectQuo(value, 'quoId')}
                  showSearch
                  optionFilterProp="children"
                >
                  {quoList.map(one => (
                    <Option
                      key={one.quoId}
                      value={one.quoId}
                      sertype={one.serType}
                      title={one.quoName}
                    >
                      {one.quoName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <LinkOutlined
              style={{
                color: batchQuery.quoId ? '#40a9ff' : 'rgb(206, 206, 206)',
                fontSize: '24px',
                position: 'absolute',
                top: '8px',
                right: '190px',
              }}
              onClick={() => this.getQuoDetail(batchQuery.quoId)} />
          </div>
          <Table
            bordered
            dataSource={quoPdList}
            columns={pdColumns}
            rowKey="pdId"
            pagination={false}
            style={{ maxWidth: 800 }}
          />
          <QutDetail
            modalVisible={modalVisible}
            handleModalVisible={this.handleModalVisible}
            detailInfo={detailInfo}
          />
          <div style={{ marginTop: 100, textAlign: 'center' }}>
            <Button
              onClick={() => router.push('/customservicemanage/adjusttask/batch')}
              style={{ marginRight: 8 }}
            >
              返回
            </Button>
            <Button type="primary" onClick={this.nextStep}>
              下一步
            </Button>
          </div>
        </Spin>
      </Form>
    );
  }
}

export default BasicForm;
